from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.x509.oid import NameOID
import datetime

# 生成较小的RSA密钥对，注意这是不安全的
private_key = rsa.generate_private_key(public_exponent=65537, key_size=512, backend=default_backend())

# 创建一个尽量简化的证书请求
subject = issuer = x509.Name([
    x509.NameAttribute(NameOID.COMMON_NAME, u"127.0.0.1"),
])

cert = x509.CertificateBuilder().subject_name(subject)\
    .issuer_name(issuer)\
    .not_valid_before(datetime.datetime.utcnow())\
    .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=30))\
    .serial_number(x509.random_serial_number())\
    .public_key(private_key.public_key())\
    .sign(private_key, SHA256(), default_backend())

# 导出为PEM格式
certificate_pem = cert.public_bytes(encoding=serialization.Encoding.PEM)

# 检查证书字符长度
print(len(certificate_pem))